#include "sortfilterproxymodel.h"
#include "wlistsourcemodel.h"
#include "wlistpatient.h"

#include <QRegExp>

SortFilterProxyModel::SortFilterProxyModel(QObject *parent) :
    QSortFilterProxyModel(parent)
{
}

bool SortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{
    QModelIndex timeIndex = sourceModel()->index(source_row, WListPatient::SchDateTime, source_parent);
    QModelIndex patientIDIndex = sourceModel()->index(source_row, WListPatient::PatientID, source_parent);
    QModelIndex patientNameIndex = sourceModel()->index(source_row, WListPatient::PatientName, source_parent);
    QModelIndex reqPhysicianIndex = sourceModel()->index(source_row, WListPatient::ReqPhysician, source_parent);
    QDateTime schTime = sourceModel()->data(timeIndex).toDateTime();
    QString pId = sourceModel()->data(patientIDIndex).toString();
    QString pName = sourceModel()->data(patientNameIndex).toString();
    QString reqPhy = sourceModel()->data(reqPhysicianIndex).toString();
    QRegExp pIdReg("*"+patientID+"*", Qt::CaseInsensitive, QRegExp::Wildcard);
    QRegExp pNameReg("*"+patientName+"*", Qt::CaseInsensitive, QRegExp::Wildcard);
    QRegExp reqPhyReg("*"+reqPhysician+"*", Qt::CaseInsensitive, QRegExp::Wildcard);
    return (!fromDate.isValid() || fromDate <= schTime) &&
            (!toDate.isValid() || toDate >= schTime) &&
            (patientID.isEmpty() || pIdReg.exactMatch(pId)) &&
            (patientName.isEmpty() || pNameReg.exactMatch(pName)) &&
            (reqPhysician.isEmpty() || reqPhyReg.exactMatch(reqPhy));
}

QVariant SortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical && role == Qt::DisplayRole) {
        return QVariant(section+1);
    } else
        return sourceModel()->headerData(section, orientation, role);
}
